package com.effectivsocial.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;

import jodd.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

import org.springframework.data.domain.Pageable;
import org.springframework.security.authentication.encoding.PasswordEncoder;

import com.effectivsocial.domain.Role;
import com.effectivsocial.domain.User;

import com.effectivsocial.repository.UserRepository;
import com.effectivsocial.service.api.AbstractService;
import com.effectivsocial.service.api.LovService;
import com.effectivsocial.service.api.UserService;

/**
 * @author Dhrubo
 * 
 */
@Named
@Slf4j
public class UserServiceImpl extends AbstractService<User, String> implements
		UserService {

	private static final long serialVersionUID = 1L;

	@Inject
	private UserRepository repository;

	@Inject
	private LovService lovService;

	@Inject
	private PasswordEncoder encoder;

	@Override
	public User save(User user) {
		includeAuditTimestamp(user);
		user.setPassword(encoder.encodePassword(user.getPassword(), null));
		return repository.save(user);
	}

	/**
	 * Rename as - addRolesToUser and rename
	 */
	@Deprecated
	@Override
	public void appendRolesToUser(User user, List<Role> roles) {
		user.setRoles(roles);
		update(user);

	}

	@Override
	public List<User> findUsersByRole(String role) {
		return null;
	}

	@Override
	public void save(List<User> entities) {
		for (User u : entities) {
			save(u);
		}

	}

	@Override
	public User findOne(String id) {
		return repository.findOne(id);
	}

	@Override
	public User findByEmail(String email) {
		return repository.findByEmail(email);
	}

	public void saveAdminUser(User user) {

		Role role = new Role();
		role.setType("ROLE");
		role.setName("ROLE_ADMIN");

		List<Role> roles = new ArrayList<Role>();
		roles.add(role);

		user.setRoles(roles);
		save(user);

	}

	@Override
	public long count() {
		return repository.count();
	}

	@Override
	public List<User> findByDeleted(Pageable pageable, boolean deleted) {
		return repository.findByDeleted(pageable, deleted);
	}

	@Override
	protected void initInternal() {
		setRepository(repository);

	}

	@Override
	public List<User> findByEmailLikeAndDeleted(String email, boolean deleted) {
		return repository.findByEmailLikeAndDeleted(email, deleted);
	}

	@Override
	public User activate(String email) {
		
		if(StringUtil.isBlank(email)) {
			throw new IllegalArgumentException("Invalid email provided.");
		}
		
		User user = repository.findByEmail(email);
		user.setActivated(true);
		user.setActivationDate(new Date());
		
		repository.save(user);
		
		return user;
	}

}
